import { PageData, IApiResult } from '../model/page-date';
import { IUser } from '../model/user';
import { config } from '../etc/config';
class HttpClient {
  baseUrl: string;
  // constructor(baseUrl: string = 'https://ec.api.59im.com') {
  //   this.baseUrl = baseUrl;
  // }

  // constructor(baseUrl: string = 'http://222.180.162.25:9001') {
  //   this.baseUrl = baseUrl;
  // }

  constructor(baseUrl: string = config.host) {
    this.baseUrl = baseUrl;
  }

  // constructor(baseUrl: string = 'http://192.168.2.44:9001') {
  //   this.baseUrl = baseUrl;
  // }

getToken(){
 return (wx.getStorageSync("userInfo") as IUser).token;
}

  async get<T>(url: string): Promise<IApiResult<T>> {
    return this.fetch<T>(url, 'GET');
  }

  async post<T>(url: string, data?: Object): Promise<IApiResult<T>> {
    return this.fetch<T>(url, 'POST', data);
  }

  async fetch<T>(url: string, method: string, data?: Object): Promise<IApiResult<T>> {
    var token = (wx.getStorageSync("userInfo") as IUser).token;
    return new Promise<IApiResult<T>>((resolve, reject) => {
      wx.request({
        header: { 'content-type': 'application/json', 'token': token },
        url: `${this.baseUrl}${url}`,
        method: method,
        data: data,
        success: (res: wx.RequestResult) => {
          if (res.statusCode != 200) {
            reject('fail');
          } else {
            resolve(res.data as IApiResult<T>);
          }
        },
        fail: (e) => {
          console.log('reqest error', e);
          wx.hideLoading();
          wx.showToast({title:'网络不给力！'})
          reject('fail');
        },
        // complete: (e) => {
        //   reject(e);
        // }
      })
    });
  }




}

export default new HttpClient();